﻿@{
	ViewBag.Title = "EventSource chat";
}

<div class="block center">
    <h2>EventSource Chat</h2>
    <div class="inputBlock center">
        <input type="text" id="msg" />
        <input class="button" id="broadcast" type="button" value="Send" />       
        <ul id="messages"></ul>
    </div>
</div>

@section scripts {
	<script type="text/javascript">
		var username = prompt('Please enter a username:');

		if (window.EventSource) {
			var source = new EventSource('@Url.Content("~/api/eventsourceapi/")');
			
			source.addEventListener('message', function (e) {
				console.log(e.data);
				var json = JSON.parse(e.data);
				$('#messages').append('<li>' + json.username + ': ' + json.message + '</li>');
				console.log('new message: ' + json.message);
			}, false);

			source.addEventListener('open', function (e) {
				console.log("open!");
			}, false);
			source.addEventListener('error', function (e) {
				if (e.readyState == EventSource.CLOSED) {
					console.log("error!");
				}
			}, false);
		} else {
			$("#messages").html("Din browser understøtter ikke EventSource");
		}

		$(document).ready(function () {
			$("#broadcast").click(function () {
				$.ajax({
					url: "@Url.Content("~/api/eventsourceapi/")",
					data: JSON.stringify({ message: $("#msg").val(), username: username }),
					cache: false,
					type: 'POST',
					dataType: "json",
					contentType: 'application/json; charset=utf-8'
				});
			});
		});
	</script>
}